package com.think.common.security.convert;

import org.springframework.core.MethodParameter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

public class DateTimeFormatQueryArgumentResolver implements HandlerMethodArgumentResolver {

    private final FormattingConversionService conversionService;

    public DateTimeFormatQueryArgumentResolver(Converter<String, Timestamp> timestampConverter) {
        DefaultFormattingConversionService service = new DefaultFormattingConversionService();
        // 注册Timestamp转换器
        service.addConverter(timestampConverter);
        this.conversionService = service;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(Timestamp.class) && parameter.hasParameterAnnotation(DateTimeFormat.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                   NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String paramName = parameter.getParameterName();
        String[] values = webRequest.getParameterValues(paramName);

        if (values != null && values.length > 0) {
            return conversionService.convert(values[0], Timestamp.class);
        }
        return null;
    }
}
